package com.e3.web.index.client;

import java.util.List;

import com.e3.web.core.client.GwtAsyncCallback;
import com.e3.web.index.model.AccordionModel;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.store.TreeStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.layout.AccordionLayout;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanelSelectionModel;
import com.google.gwt.user.client.Element;

public class MainAccordion extends LayoutContainer{
	
	private MainFrameServiceAsync service = MainFrameService.Util.getInstance();
	
	@Override
	protected void onRender(Element parent, int index) {
		super.onRender(parent, index);
		this.setLayout(new AccordionLayout());
		
		initAccordion();
	}

	private void initAccordion() {
		service.getAllAccordionModels(new GwtAsyncCallback<List<AccordionModel>>(this) {
			public void doSuccess(List<AccordionModel> result) {
				drawAccordion(result);
			}
		});
	}
	
	private void drawAccordion(List<AccordionModel> models){
		if(models!=null&&models.size()>0){
			for (AccordionModel accordionModel : models) {
				ContentPanel cp = new ContentPanel(new FitLayout());
				cp.setHeading(accordionModel.getName());
				
				TreeStore<AccordionModel> store = new TreeStore<AccordionModel>();   
			    TreePanel<AccordionModel> tree = new TreePanel<AccordionModel>(store);
			    TreePanelSelectionModel<AccordionModel> sm = new TreePanelSelectionModel<AccordionModel>(); 
			    tree.setSelectionModel(sm);
			    tree.setDisplayProperty("name");
			    store.add(accordionModel, true);
			    tree.setExpanded(accordionModel, true);
			    
			    cp.add(tree);
			    this.add(cp);
			    
			    sm.addSelectionChangedListener(new SelectionChangedListener<AccordionModel>() {
					@Override
					public void selectionChanged(SelectionChangedEvent<AccordionModel> se) {
						AccordionModel model = se.getSelectedItem();
						if(model == null){
							return;
						}
						if(model.isLeaf()){
							NavigatorHelper.onElementSelected(model, model.getName());
						}
					}
				});
			}
		}
		this.layout(true);
	}
	
}
